package crap;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Erklaerer01 {
	public static void main(String[] args) {
		try {
			BufferedImage bi = ImageIO.read(new File("/Users/supersublimer/Documents/workspace/ComputerVision2011/bild.jpg"));
			
			final int w = bi.getWidth(), h = bi.getHeight();

			int[] pixels = bi.getRGB(0, 0, w, h, new int[w*h], 0, w);
			
			float[] y = new float[w*h], u = new float[w*h], v = new float[w*h];
			
			//ARGB
			//AARRGGBB 0xFF000000 => 0x0000FFRR&0x000000FF => 0x000000RR
			//0xFF == 0x000000FF
			
			for (int i = 0; i<pixels.length; i++) {
				int rgb = pixels[i];
				int r = (rgb>>16)&0xFF, g = (rgb>>8)&0xFF, b = rgb&0xFF;
				float red = r/255f, green = g/255f, blue = b/255f;
				y[i] = 0.299f*red+0.587f*green+0.114f*blue;
				u[i] = (blue-y[i])*0.493f;
				v[i] = (red-y[i])*0.877f;
			}

			final BufferedImage uvh = new BufferedImage(256, 256,	BufferedImage.TYPE_INT_ARGB);
			
			int[] data = new int[256*256];
			
			for (int i = 0; i<pixels.length; i++) {
				int uindex = ((int)(u[i]*255))&0xFF, vindex = ((int)(v[i]*255))&0xFF;
				data[vindex+uindex*256]++;
			}
			for (int i = 0; i<pixels.length; i++) {
				data[i] = data[i] | 0xFF000000;
			}
				
			uvh.setRGB(0, 0, 256, 256, data, 0, 256);
			
			JFrame frame = new JFrame();
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			
			
			frame.add(new JComponent() {
				{setPreferredSize(new Dimension(uvh.getWidth()*4,uvh.getHeight()*4));}
				@Override
				public void paint(Graphics g) {
					g.drawImage(uvh.getScaledInstance(1024, 1024, BufferedImage.SCALE_FAST), 0, 0, this);
					super.paint(g);
				}
			});
			
			frame.pack();
			frame.setVisible(true);
		}
		catch (IOException iox) {
			iox.printStackTrace();
		}
	}
}
